package cn.dapeng.rpc.common.serial;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class JDKSerializeCoder {

    private static ByteArrayOutputStream out = new ByteArrayOutputStream();

    public synchronized static byte[] serial(Object msg) {
        out.reset();

        try (ObjectOutputStream oout = new ObjectOutputStream(out)) {
            oout.writeObject(msg);
            return out.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public synchronized static <T> T deseria(byte[] bytes, Class<T> clazz) throws Exception {

        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
             ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)
        ) {
            return (T) objectInputStream.readObject();
        }

    }
}
